import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
instance.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  (error) => {
    // do something with request error
    // console.log(error) // for debug
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

// response interceptor
instance.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // Token 401处理
    // console.dir(error.response.status)
    if (error.response.status === 401) {
      // 1. 清空用户数据
      store.commit('user/SET_TOKEN', '')
      // 2. 跳转到登录
      router.push(`/login?redirect=${this.$route.fullPath}`)
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default instance
